package org.example.domain.service.impl;

import com.google.common.util.concurrent.AtomicDouble;
import jakarta.annotation.Resource;
import org.example.domain.service.OpenRankServiceDomain;
import org.example.entity.openrank.DataNode;
import org.example.vo.CommunityOpenRankVO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: OpenRak 服务实现类
 * Created by 陈宇 on 2024-12-27 15:27
 * Created with IntelliJ IDEA.
 * @author 陈宇
 */
@Service
public class OpenRankServiceDomainImpl implements OpenRankServiceDomain {

    @Resource
    private RestTemplate httpRest;
    @Resource(name = "mapCacheManager")
    private ConcurrentHashMap<String, ConcurrentHashMap<String, Object>> cacheManager;

    @Override
    public CommunityOpenRankVO queryCommunityOpenRank(String platform, String repo) {
        String url = "https://oss.open-digger.cn/{1}/{2}/community_openrank.json";
        HttpHeaders httpHeaders = new HttpHeaders();

        // 获取 社区 OpenRank
        ResponseEntity<CommunityOpenRankVO> response = httpRest.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders), CommunityOpenRankVO.class, platform, repo);
        if (response.getStatusCode().is2xxSuccessful()) {
            CommunityOpenRankVO communityOpenRankVO = response.getBody();

            // 对获取到的 communityOpenRank 做处理
            // 1. 取出其中元数据的节点
            List<List<String>> nodes = communityOpenRankVO.getMeta().getNodes();
            Double id = 0.0;
            cacheManager.get("nodeId").clear();
            // 1.1 对其中的所有节点进行编号，并存入缓存中（节点 id，编号）
            for (List<String> node : nodes) {
                mapId2PlatformId(String.valueOf(id), node);
                mapPlatformId2Id(String.valueOf(id++), node);
            }
//            nodes.stream().forEach(n -> {
//                mapId2PlatformId(String.valueOf(id.get()), n);
//                mapPlatformId2Id(String.valueOf(id.getAndAdd(1)), n);
//            });
            // 2. 取出其中的数据节点
            Map<String, DataNode> data = communityOpenRankVO.getData();
            // 2.1 将数据存入缓存
            StringBuilder sb = new StringBuilder();
            sb.append(platform).append("/").append(repo);
            String key = sb.toString();
            cacheManager.get("communityOpenRankCache").put(key, data);
            return communityOpenRankVO;
        }
        // 如果返回不是 2XX，说明 api 有异常，往外抛出
        throw new RuntimeException("open-digger API 异常");
    }

    /**
     * 返回仓库 id
     */
    @Override
    public String getRepoId(String platform, String repo) {
        String url = "https://oss.open-digger.cn/{1}/{2}/community_openrank.json";
        HttpHeaders httpHeaders = new HttpHeaders();

        // 获取 社区 OpenRank
        ResponseEntity<CommunityOpenRankVO> response = httpRest.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders), CommunityOpenRankVO.class, platform, repo);
        if (response.getStatusCode().is2xxSuccessful()) {
            CommunityOpenRankVO communityOpenRankVO = response.getBody();
            return communityOpenRankVO.getMeta().getRepoId();
        } else {
            return null;
        }
    }

    /**
     * 将平台 id 映射到顺序 id
     * @param node 节点
     * @param id 平台 id
     * @return 顺序 id
     */
    private String mapId2PlatformId(String id, List<String> node) {
        String s = node.get(0);
        cacheManager.get("nodeId").put(id, s);
        return s;
    }

    /**
     * 将顺序 id 映射到 平台 id
     */
    private String mapPlatformId2Id(String id, List<String> node) {
        String s = node.get(0);
        cacheManager.get("nodeIdR").put(s, id);
        return s;
    }

}
